package com.example.demo01.controller;

import com.example.demo01.dao.DepartmentDao;
import com.example.demo01.dao.EmployeeDao;
import com.example.demo01.entities.Department;
import com.example.demo01.entities.Employee;
import com.sun.org.apache.xpath.internal.operations.Mod;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * @author 王迅
 */
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private DepartmentDao departmentDao;

    /**
     * 查询员工所有信息
     */
    @GetMapping(path = "/emps")
    public String list(Model model) {
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps", employees);
        return "emp/list";
    }

    /**
     * 来到添加页
     */
    @GetMapping(path = "/emp")
    public String toAddPage(Model model) {
        // TODO: 来到添加页面之前，查出所有的部门，在页面显示
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departs", departments);
        return "emp/add";
    }

    /**
     * 添加员工
     */
    @PostMapping(path = "/emp")
    public String addEmp(Employee employee) {
        // TODO: 保存员工信息
        employeeDao.save(employee);
        // TODO: 添加完成来到员工页表页面
        return "redirect:/emps";
    }

    /**
     * 来到修改页
     */
    @GetMapping(path = "/emp/{id}")
    public String toEditPage(@PathVariable Integer id, Model model) {
        // TODO: 来到修改页面之前，查出所有的部门，在页面显示
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departs", departments);
        // TODO: 根据 id 查询员工
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp", employee);
        // TODO: add.html 是一个 {修改 | 添加} 二合一的页面
        return "emp/add";
    }

    /**
     * 员工修改
     */
    @PutMapping(path = "/emp")
    public String updateEmployee(Employee employee) {
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    /**
     * 删除员工
     */
    @DeleteMapping(path = "/emp/{id}")
    public String deleteEmployee(@PathVariable Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
